package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Bank;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by anton on 8/22/14.
 */
public class BankServer {
    public static void startServer(Bank bank) {
        System.out.println("Starting server, waiting for connection...");
        try(ServerSocket socketListener = new ServerSocket(5512)) {
            Socket socket = socketListener.accept();
            System.out.println("Connected");

            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            loop1:
            while(true) {
                String message = reader.readLine();
                System.out.println(message);
                switch (message) {
                    case "quit":
                        break loop1;
                    case "show clients":
                        String clientsInfo = bank.getClientsInfo();
                        writer.write("Server response:\n" + clientsInfo);
                        writer.newLine();
                        writer.flush();
                        break;
                    default:
                        writer.write("No such a command");
                        writer.newLine();
                        writer.flush();
                        break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
